package com.education.web.auth.service;


import com.education.web.auth.fegin.SystemAdminFeign;
import com.education.web.common.core.utils.ObjectUtils;
import com.education.web.common.core.utils.ResultCode;
import com.education.web.common.core.utils.Result;
import com.education.web.common.security.exception.WebOAuth2Exception;
import com.education.web.dto.AdminUserSession;
import com.education.web.dto.SystemSecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.*;


/**
 * @author zengjintao
 * @version 1.0
 * @create_at 2019/9/15 14:50
 */
@Service
public class SystemUserDetailService implements UserDetailsService {

    @Autowired
    private SystemAdminFeign systemAdminFeign;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        Result<AdminUserSession> result = systemAdminFeign.selectByName(userName);
        if (ObjectUtils.isEmpty(result)) {
            throw new WebOAuth2Exception(new ResultCode(ResultCode.FAIL, "服务异常"));
        }
        AdminUserSession adminUserSession = result.getData();
        if (ObjectUtils.isEmpty(adminUserSession)) {
            throw new WebOAuth2Exception(new ResultCode(ResultCode.FAIL, "用户不存在"));
        }

        Set<String> permissionList = adminUserSession.getPermissionList();
        SystemSecurityUser systemSecurityUser = new SystemSecurityUser(adminUserSession,
                getGrantedAuthorities(permissionList));
        return systemSecurityUser;
    }


    /**
     * 加载用户权限
     * @param permissionList
     * @return
     */
    public final List<GrantedAuthority> getGrantedAuthorities(final Set<String> permissionList) {
        final List<GrantedAuthority> authorities = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(permissionList)) {
            permissionList.forEach(permission -> {
               authorities.add(new SimpleGrantedAuthority(permission));
            });
        }
        return authorities;
    }
}
